#include "nvds_pipeline.h"
#include "nvds_pipeline_builder.h"
#include "nvds_sourcebin.h"
#include <boost/filesystem.hpp>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <memory>
#include <spdlog/spdlog.h>
#include <thread>
using namespace std;

void result_callback(const std::vector<DetectResult> &result_datas)
{
    spdlog::info("**********************************");
    spdlog::info("stream\tframe\ttarget\timgsize\tntp\tland\tdetect\tfinish\tcost(ms)");
    for (int i = 0; i < result_datas.size(); i++) {
        auto costTime = result_datas[i].nvds_over_time - result_datas[i].landing_time;
        // auto costTime = result_datas[i].nvds_over_time - result_datas[i].ntp_timestamp / 1000000;
        spdlog::info("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}",
                     result_datas[i].device_id,
                     result_datas[i].frame_id,
                     result_datas[i].objects.size(),
                     result_datas[i].image_data.data.size(),
                     result_datas[i].ntp_timestamp / 1000000,
                     result_datas[i].landing_time,
                     result_datas[i].detection_time,
                     result_datas[i].nvds_over_time,
                     costTime);
    }
}

int main(int argc, char *argv[])
{
    // 设置日志输出级别
    spdlog::level::level_enum log_level     = spdlog::level::info;
    const char               *env_log_level = std::getenv("SPDLOG_LEVEL");
    if (env_log_level != nullptr) {
        if (strcmp(env_log_level, "trace") == 0)
            log_level = spdlog::level::trace;
        else if (strcmp(env_log_level, "debug") == 0)
            log_level = spdlog::level::debug;
        else if (strcmp(env_log_level, "info") == 0)
            log_level = spdlog::level::info;
        else if (strcmp(env_log_level, "warn") == 0)
            log_level = spdlog::level::warn;
        else if (strcmp(env_log_level, "error") == 0)
            log_level = spdlog::level::err;
        else if (strcmp(env_log_level, "off") == 0)
            log_level = spdlog::level::off;
    }
    spdlog::set_level(log_level);

    auto pipeline = std::make_shared<NVDSPipeline>();
    pipeline->setCallback(result_callback);

    // 启动 pipeline
    std::thread([pipeline]() {
        pipeline->start("./deepstream_config.yml");
    }).detach();

    while (char c = cin.get()) {
        if (c == 'q' || c == 'Q')
            break;
    }
    pipeline->stop();
    return 0;
}